package com.huawei.aiosproj.view;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide; // Import Glide
import com.huawei.aiosproj.R;

import java.util.Collections;
import java.util.List;
import java.util.ArrayList;

public class CardAdapter extends RecyclerView.Adapter<CardAdapter.CardViewHolder> {
    private List<CardItem> cardItems;
    private Context context;
    private static final String TAG = CardAdapter.class.getSimpleName();

    public CardAdapter(List<CardItem> cardItems, Context context) {
        this.cardItems = cardItems;
        this.context = context;
    }

    public CardItem getItem(int position) {
        if (cardItems != null && position >= 0 && position < cardItems.size()) {
            return cardItems.get(position);
        }
        return null;
    }

    public void updateData(List<CardItem> newCardItems) {
        this.cardItems.clear();
        this.cardItems.addAll(newCardItems);
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public CardViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_card, parent, false);
        return new CardViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull CardViewHolder holder, int position) {
        CardItem card = cardItems.get(position);
        holder.bind(card, context);

        holder.itemView.setOnClickListener(v -> {
            int clickedPosition = holder.getAdapterPosition();

            if (clickedPosition == RecyclerView.NO_POSITION || cardItems == null || cardItems.isEmpty()) {
                Log.d(TAG, "onClick: Invalid position or empty items.");
                return;
            }

            int lastPosition = cardItems.size() - 1;

            // If the clicked item is already at the last position, do nothing.
            if (clickedPosition == lastPosition) {
                Log.d(TAG, "onClick: Clicked item is already at the last position.");
                return;
            }

            // Ensure there are at least two items to perform the swap.
            if (cardItems.size() < 2) {
                Log.d(TAG, "onClick: Not enough items to perform the move operation.");
                return;
            }

            // --- Perform the data swap ---
            // The item at clickedPosition will move to lastPosition,
            // and the item at lastPosition will move to clickedPosition.
            Collections.swap(cardItems, clickedPosition, lastPosition);

            // --- Notify the adapter about the changes ---
            // We need to notify that the items at BOTH positions have changed.
            // This tells RecyclerView to rebind the ViewHolders at these positions
            // with the new data from the swapped items.
            notifyItemChanged(clickedPosition);
            notifyItemChanged(lastPosition);

            // Optional: Scroll to make the items visible if they moved out of view.
            // If the clicked item (now at the end) needs to be visible:
            // ((RecyclerView) v.getParent()).scrollToPosition(lastPosition);
            // Or if the item that moved to clickedPosition needs to be visible:
            // ((RecyclerView) v.getParent()).scrollToPosition(clickedPosition);

            Log.d(TAG, "onClick: Item swap complete. Item from " + clickedPosition +
                    " swapped with item from " + lastPosition);
        });
    }

    @Override
    public int getItemCount() {
        return cardItems == null ? 0 : cardItems.size();
    }

    // Method to get the first item (e.g., for making a call)
    public CardItem getFirstItem() {
        if (cardItems != null && !cardItems.isEmpty()) {
            return cardItems.get(0);
        }
        return null;
    }


    static class CardViewHolder extends RecyclerView.ViewHolder {
        // Assuming item_card.xml primarily uses views with "Front" in their ID
        // If cardBack views exist and are not needed, they can be removed from here and item_card.xml
        LinearLayout cardFront; // If card_front is the root of your item layout.
        TextView poiNameFront, poiAddressFront, poiPhoneFront;
        ImageView poiPhotoFront;

        public CardViewHolder(@NonNull View itemView) {
            super(itemView);
            // If your item_card.xml's root is the card front itself (e.g., a LinearLayout or CardView)
            // then cardFront = (LinearLayout) itemView; or similar.
            // If R.id.cardFront is a specific child LinearLayout within itemView:
            cardFront = itemView.findViewById(R.id.cardFront);

            // It's crucial that R.id.cardFront and other "Front" views are correctly defined in your item_card.xml
            // and that there's no R.id.cardBack or similar that would be shown.
            poiNameFront = itemView.findViewById(R.id.poiNameFront);
            poiAddressFront = itemView.findViewById(R.id.poiAddressFront);
            poiPhoneFront = itemView.findViewById(R.id.poiPhoneFront);
            poiPhotoFront = itemView.findViewById(R.id.poiPhotoFront);

            // It's good practice to check if critical views are found
            if (cardFront == null) Log.e(TAG, "CardViewHolder: cardFront view not found.");
            if (poiNameFront == null) Log.e(TAG, "CardViewHolder: poiNameFront view not found.");
            // Add checks for other views as needed
        }

        public void bind(CardItem card, Context context) {
            // Ensure you are binding to the correct views.
            // If cardFront was itemView itself, then itemView.setBackgroundResource(...)
            if (cardFront != null) cardFront.setBackgroundResource(card.getColorRes());
            // else itemView.setBackgroundResource(card.getColorRes()); // if itemView is the card front

            if (poiNameFront != null) poiNameFront.setText(card.getName());
            if (poiAddressFront != null) poiAddressFront.setText(card.getAddress());
            if (poiPhoneFront != null) poiPhoneFront.setText(card.getPhone());

            if (poiPhotoFront != null && card.getPhotoUrl() != null && !card.getPhotoUrl().isEmpty()) {
                Glide.with(context)
                        .load(card.getPhotoUrl())
                        .placeholder(R.drawable.card_gradient_1) // Placeholder image
                        .error(R.drawable.card_gradient_2)       // Error image
                        .into(poiPhotoFront);
            } else if (poiPhotoFront != null) {
                // Clear previous image and set a default or hide
                Glide.with(context).clear(poiPhotoFront);
                poiPhotoFront.setImageResource(R.drawable.card_gradient_3); // Default image if no photo
            }
        }
    }
}
